//
//  MTNativeStoreSearchViewController.m
//  ebook
//
//  Created by 吴超飞 on 2017/3/15.
//  Copyright © 2017年 Moton. All rights reserved.
//

#import "MTNativeStoreSearchViewController.h"
#import "LayoutCellTable.h"
#import "LayoutCellScroll.h"
#import "LayoutCellList.h"
#import "LayoutCellTableAndList.h"
#import "LayoutCellDualList.h"
#import "LayoutCellAd.h"
#import "EbookNetRequest.h"
#import "MTStoreDetailViewController.h"
#import "MJRefresh.h"
#import "SearchTableViewCell.h"
#import "NativeSortNameManage.h"

@interface MTNativeStoreSearchViewController ()<UISearchBarDelegate, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource,LayoutCellBaseDelegate>{
    
    BOOL hasSearch;//是否开始了搜索
    
    int page;//搜索结果当前分页
    int totoalPage;//搜索结果总页数
    int totoalCount;//搜索结果总数
}

@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, copy) NSString *searchText;

//初始化显示的默认视图
@property (nonatomic, strong) UITableView *defaultTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

//搜索联想视图
@property (nonatomic, retain) UITableView *resultTableView;
@property (nonatomic, retain) NSMutableArray *searchResults;

//搜索结果视图
@property (nonatomic, strong) UITableView *bookTableView;
@property (nonatomic, retain) NSMutableArray *bookData;

@end

@implementation MTNativeStoreSearchViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    [self createBackBtn];
    [self createSearchBar];
    [self.view addSubview:self.defaultTableView];
    [self getLayoutData];
}

-(UITableView *)tableViewInstance{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH-64) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    return tableView;
}

- (UITableView *)defaultTableView {
    
    if (!_defaultTableView) {
        _defaultTableView = [self tableViewInstance];
    }
    return _defaultTableView;
}

-(UITableView *)resultTableView{
    
    if(!_resultTableView){
        _resultTableView = [self tableViewInstance];
        _resultTableView.tableFooterView = [[UIView alloc]init];
        _resultTableView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.95];
        _resultTableView.scrollEnabled = NO;
        _resultTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _resultTableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    }
    return _resultTableView;
}

-(UITableView *)bookTableView{
    
    if (!_bookTableView) {
        _bookTableView = [self tableViewInstance];
        _bookTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self getSearchResult:_searchText];
        }];
    }
    return _bookTableView;
}

#pragma mark - backBtn
- (void)createBackBtn {
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - searchBar
- (void)createSearchBar
{
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.contentMode = UIViewContentModeLeft;
    searchBar.placeholder = @"输入书名/作者";
    searchBar.delegate = self;
    _searchBar = searchBar;
    [searchBar becomeFirstResponder];
    
    self.navigationItem.titleView = searchBar;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    if([searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length==0)return;
    
    [searchBar resignFirstResponder];
    [self.resultTableView removeFromSuperview];
    [self.view addSubview:self.bookTableView];
    
    _searchText = searchBar.text;
    hasSearch = YES;
    page = 1;
    totoalPage = 2;
    
    [self showHud];
    [self getSearchResult:_searchText];
}

//搜索联想
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    MTLog(@"searchText:%@",searchText);
    if (0 == searchText.length) {
        
        [_searchResults removeAllObjects];
        [self.resultTableView reloadData];
        [self.resultTableView removeFromSuperview];
        
        [_bookData removeAllObjects];
        [self.bookTableView reloadData];
        [self.bookTableView removeFromSuperview];
    }else{
        
        hasSearch = NO;
        [EbookNetRequest searchText:searchText resultSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
            NSArray *result = [dict objectForKey:@"list"];
            if(![result isKindOfClass:[NSNull class]] && result.count>0){
                
                if(!_searchResults)_searchResults = [NSMutableArray array];
                [_searchResults removeAllObjects];
                [_searchResults addObjectsFromArray:result];
                [self.resultTableView reloadData];
                self.resultTableView.height = self.searchResults.count*44;
                self.resultTableView.y = 0;
                
                if(!hasSearch){
                    [self.view addSubview:self.resultTableView];
                }
            }
        } failed:^(int stateCode, NSString *failMsg) {
            MTLog(@"");
        }];
    }
}

-(void)getSearchResult:(NSString *)searchText{
    
    if(page >= totoalPage)return;
    searchText = [searchText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [EbookNetRequest searchResultText:searchText currentPage:page pageSize:10 resultSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        if(!_bookData)_bookData = [NSMutableArray array];
        if(page==1)[_bookData removeAllObjects];
        
        totoalPage = [dict[@"resp"][@"Pagecount"] intValue];
//        page = [dict[@"currentpage"] intValue];
        totoalCount = [dict[@"resp"][@"Itemcount"] intValue];
        page++;
        
        NSArray *books = dict[@"resp"][@"Results"];
        for (NSDictionary *dict in books) {
            StoreBookModel *model = [StoreBookModel yy_modelWithJSON:dict];
            model.sortName = [[NativeSortNameManage shareInstance] getSortnameWithSortid:model.Sortid];
            [_bookData addObject:model];
        }
        
        [self.bookTableView reloadData];
        [self hideHud];
    } failed:^(int stateCode, NSString *failMsg) {
        [self hideHud];
    }];
}

- (NSDictionary *)getDefaultDic {
    
    id data = [[NSUserDefaults standardUserDefaults] objectForKey:KBookCityData];
    return  [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [_searchBar resignFirstResponder];
}

//获取布局信息
- (void)getLayoutData {
    
    [self showHud];
    _dataArray = [NSMutableArray array];
    
    [EbookNetRequest searchLayoutSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        NSArray *resp = dict[@"resp"];
        
        for (NSDictionary *dic in resp) {
            LayoutType *model = [LayoutType yy_modelWithDictionary:dic];
            [_dataArray addObject:model];
        }
        
        [self.defaultTableView reloadData];
        [self hideHud];
    } failed:^(int stateCode, NSString *failMsg) {
        [self showFailedView];
    }];
}

- (void)reloadView {
    
    [self hideFailedView];
    [self getLayoutData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView == self.defaultTableView) {
        return _dataArray.count;
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.defaultTableView) {
        return 1;
    }else if(tableView == self.bookTableView){
        return _bookData.count;
    }else if(tableView == self.resultTableView){
        return _searchResults.count;
    }
    
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.defaultTableView && section != 0) {
        return 10.0f;
    }else if(tableView == self.bookTableView){
        return 44.0f;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.bookTableView) {
        
        UIView *view = [UIView new];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(LayoutSpaceOut, 0, MTScreenW-LayoutSpaceOut*2, 44)];
        label.text = [NSString stringWithFormat:@"共搜到%d条结果",totoalCount];
        [view addSubview:label];
       
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(tableView == self.bookTableView){
        
        return kLayoutCellListItemHeight;
        
    }else if(tableView == self.defaultTableView){
        
        if(indexPath.section<_dataArray.count){
            
            LayoutType *layout = _dataArray[indexPath.section];
            
            switch (layout.type) {
                case 1:
                    return [LayoutCellTable viewHeight:layout];
                    break;
                case 2:
                    return [LayoutCellList viewHeight:layout];
                    break;
                case 3:
                    return [LayoutCellTableAndList viewHeight:layout];
                    break;
                case 4:
                    return [LayoutCellScroll viewHeight:layout];
                    break;
                case 5:
                    return [LayoutCellDualList viewHeight:layout];
                    break;
                case 0:
                    return [LayoutCellAd viewHeight:layout];
                    break;
                    
                default:
                    break;
            }
        }
    }else if (tableView == self.resultTableView){
        
        return 44;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(tableView == self.bookTableView){
        
        LayoutCellListItem *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
        if (!cell) {
            cell = [[LayoutCellListItem alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellId isShowCoverImage:YES];
        }
        StoreBookModel *model = [self.bookData objectAtIndex:indexPath.row];
        cell.model = model;
        
        return cell;
    }else if(tableView == self.defaultTableView){
        
        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", (int)[indexPath section], (int)[indexPath row]];//以indexPath来唯一确定cell
        LayoutCellBase *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        LayoutType *layout = [_dataArray objectAtIndex:indexPath.section];
        
        if(!cell){
            switch (layout.type) {
                case 1:
                    cell = [[LayoutCellTable alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                    break;
                case 2:
                    cell = [[LayoutCellList alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                    break;
                case 3:
                    cell = [[LayoutCellTableAndList alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                    break;
                case 4:
                    cell = [[LayoutCellScroll alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                    break;
                case 5:
                    cell = [[LayoutCellDualList alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                    break;
                case 0:
                    cell = [[LayoutCellAd alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier withDict:layout.ad inController:self];
                    break;
                default:
                    break;
            }
        }
        
        if(layout.type!=0)
            cell.layOutType = layout;
        cell.delegate = self;
        
        return cell;
    }else if(tableView == self.resultTableView){
        
        SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
        if (!cell) {
            cell = [[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor clearColor];
        }
        NSDictionary *dict = self.searchResults[indexPath.row];
        cell.textLabel.text = dict[@"Name"];
        
        return cell;
    }
    
    return [UITableViewCell new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView==self.bookTableView && indexPath.row < self.bookData.count) {
        
        StoreBookModel *model = self.bookData[indexPath.row];
        [self layoutCellBase:nil didSelectModel:model];
    }else if(tableView == self.resultTableView && indexPath.row < self.searchResults.count){
        
        NSDictionary *dict = self.searchResults[indexPath.row];
        _searchBar.text = dict[@"Name"];
        [self searchBarSearchButtonClicked:_searchBar];
    }
}

#pragma mark - LayoutCellBaseDelegate
-(void)layoutCellBase:(LayoutCellBase *)cell didSelectModel:(StoreBookModel *)model{
    
    MTLog(@"点击书籍：%@",model);
    MTStoreDetailViewController *resultVc = [[MTStoreDetailViewController alloc] init];
    resultVc.title = model.Name;
    resultVc.model = model;
    [self.navigationController pushViewController:resultVc animated:YES];
}

-(void)layoutCellBase:(LayoutCellBase *)cell moreBtnClick:(UIButton *)btn{
    
}


@end
